package com.java.test.utils;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImageWord {

    public static void main(String[] args) throws IOException {
        int left = 720;
        int top = 1279;
        int fontSize = 50;
        Map<String,String> strMap = new HashMap<>();
        for(String strIn :args){
            String[] sm = strIn.split("=");
            if(sm.length==2){
                strMap.put(sm[0],sm[1]);
            }
        }
        if(strMap.containsKey("left")) {
            try{
                left = Integer.valueOf((String) strMap.get("left"));
            }catch (NumberFormatException e){
                System.out.println("left非法");
            }
        }
        if(strMap.containsKey("top")) {
            try{
                top = Integer.valueOf((String) strMap.get("top"));
            }catch (NumberFormatException e){
                System.out.println("top非法");
            }
        }
        if(strMap.containsKey("fontSize")) {
            try{
                fontSize = Integer.valueOf((String) strMap.get("fontSize"));
            }catch (NumberFormatException e){
                System.out.println("fontSize非法");
            }
        }

        System.out.println("设置的字位置 left="+left+";top="+top+",设置字体大小:"+fontSize);

        List<Map> list = new ArrayList<Map>();

        String USER_DIR= System.getProperty("user.dir");
        System.out.println("USER_DIR:"+USER_DIR);
        String INPUT_DIR = "pictures";
        String OUTPUT_DIR = "pictures-copy";
        File inputDic = new File(USER_DIR+"/"+INPUT_DIR);
        File outputDic = new File(USER_DIR+"/"+OUTPUT_DIR);
        if(!inputDic.exists()){
            System.out.println("warning:'pictures' directory does not exist ");
            System.out.println("alert: please create  'pictures' directory  and put pictures in this directory ");
            return ;
        }else{
            if(!outputDic.exists()){
                outputDic.mkdir();
            }
            String[] files = inputDic.list();
            for (int i = 0; i < files.length; i++) {// 循环，添加文件名或回调自身
                File file = new File(inputDic, files[i]);
                if (file.isFile()) {// 如果文件
                    Map<String,String> map = new HashMap<String,String>();
                    String fileNameSimple = file.getName();
                    //System.out.println(fileNameSimple.lastIndexOf("."));
                    String fileNameInput = inputDic + "\\" + fileNameSimple;// 添加文件全路径名
                    String fileNameOutput = outputDic + "\\" + fileNameSimple;// 添加文件全路径名
                    map.put("fileNameInput",fileNameInput);
                    map.put("fileNameOutput",fileNameOutput);
                    map.put("text",fileNameSimple.substring(0,fileNameSimple.lastIndexOf(".")));
                    list.add(map);
                }
            }
        }
        String CON_File = "configuration.txt";
        File configurationFile = new File(USER_DIR+"/"+CON_File);
        if(configurationFile.exists()){//加载配置文件，从pictures中加载picture，并将对应的文字加入picture中

        }

        Long startTime = System.currentTimeMillis();
          for(Map<String,String> map:list){
              String fileNameInput = map.get("fileNameInput");
              String fileNameOutput = map.get("fileNameOutput");
              String text = map.get("text");
              drawTextInImg(fileNameInput,fileNameOutput,text,left,top,fontSize);
          }

        //drawTextInImg("123456789");
        Long endTime = System.currentTimeMillis();
        long interval = (endTime - startTime)/1000;
        System.out.println("修改"+list.size()+"张图片，总共用时:"+interval+"s");
    }


    public static void drawTextInImg(String fileNameInput,String fileNameOutput,String text,int left,int top,int fontSize) {
        Long startTime = System.currentTimeMillis();
        System.out.print("图片["+fileNameInput+"]修改开始;即将添加文字["+text+"]");
        String filePath = fileNameInput;//"C:\\Users\\sailor\\Desktop\\1.jpg";
        //String filePath = "/root/jars/IMG_7205.png";
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image img = imgIcon.getImage();
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        //System.out.println("width:"+width+"-->height:"+height);
        BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        g.setColor(getColor("#ffffff"));
        g.setBackground(Color.white);
        g.drawImage(img, 0, 0, null);
        //设置字体样式，风格，大小
        Font font = new Font("宋体",Font.BOLD,fontSize);
        g.setFont(font);
        //以左上角为坐标轴原点，left为横坐标，top为纵坐标
        //抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawString(text, left, top);
       /* //绘制开始时间
        g.drawString(startTime, left, top);
        //绘制结束时间
        g.drawString(endTime, left, top+65);*/
        //释放对象
        g.dispose();
        try {
            //BufferedImage 转 InputStream
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(bimage, "png", imageOutput);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            long length = imageOutput.length();
            //设置response
           /* response.setContentType("image/png");
            response.setContentLength((int)length);
            response.setHeader("Content-Disposition","attachment;filename="+new String("license.png".getBytes("gbk"),"iso-8859-1"));*/
            //输出流
            byte[] bytes = new byte[1024];
            OutputStream outputStream  = new FileOutputStream(fileNameOutput);//"C:\\Users\\sailor\\Desktop\\1-1.jpg"
            long count = 0;
            while(count < length){
                int len = inputStream.read(bytes, 0, 1024);
                count +=len;
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
        } catch (Exception e){
            e.printStackTrace();
        }
        System.out.print("-----文字修改结束;");
        Long endTime = System.currentTimeMillis();
        long interval = (endTime - startTime);
        System.out.println("用时:"+interval+"毫秒");
        System.out.println("**********************");

    }
    public static Color getColor(String color) {
        if (color.charAt(0) == '#') {
            color = color.substring(1);
        }
        if (color.length() != 6) {
            return null;
        }
        try {
            int r = Integer.parseInt(color.substring(0, 2), 16);
            int g = Integer.parseInt(color.substring(2, 4), 16);
            int b = Integer.parseInt(color.substring(4), 16);
            return new Color(r, g, b);
        } catch (NumberFormatException nfe) {
            return null;
        }
    }


}
